package com.wenguo.action.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wenguo.Constants;
import com.wenguo.bussines.model.Log;
import com.wenguo.bussines.model.ResultMessage;
import com.wenguo.bussines.model.User;
import com.wenguo.common.util.BeansUtil;
import com.wenguo.exception.WenGuoException;

@Controller
@RequestMapping("/user/*")
public class LoginAction extends BaseAction {

	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(User user, HttpServletRequest request, Model model){
		try {
			User u = facade.login(user);
			if(null != u) {
				request.getSession().setAttribute(Constants.system.USER, u);
				Log log = BeansUtil.getLogInfo(u, request);
				facade.WriteLog(log);
				u.setLast(log.getDate());
				facade.updateUser(u);
				return "user/main";
			}
		} catch (WenGuoException e) {
			logger.error(e);
		}
		model.addAttribute(Constants.system.TIPS, "account/password incrrect!");
		return "/index";
	}
	
	@RequestMapping(value="logout",method=RequestMethod.GET)
	public String logout(HttpServletRequest request){
		request.getSession().removeAttribute(Constants.system.USER);
		return "/index";
	}
	
	@RequestMapping(value="securityCode",method=RequestMethod.POST)
	public @ResponseBody ResultMessage validSecurityCode(@RequestParam String scode,
			HttpServletRequest request){
		ResultMessage rm = new ResultMessage();
		if (!BeansUtil.checkSecurityCode(request, scode)) {
			rm.setReturnCode(Constants.status.FAILED);
		}
		return rm;
	}
	
}
